package org.gp.core.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import lombok.extern.slf4j.Slf4j;
import org.gp.core.annotation.AuthOperate;
import org.gp.core.entity.OpenId;
import org.gp.core.entity.User;
import org.gp.core.entity.WxUserInfo;
import org.gp.core.entity.dto.ResponseDTO;
import org.gp.core.entity.result.UserInfoResult;
import org.gp.core.service.IUserService;
import org.gp.core.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表  前端控制器
 * </p>
 *
 * @author LuoLiang
 * @since 2017-01-24
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private IWechatService wechatService;
    @Resource
    private IUserService userService;
    @Value("${wechat.index_url}")
    private String INDEX_URL;
    @Value("${wechat.domain}")
    private String domain;

    /**
     * 用户打开应用，验证用户信息
     * 如果为首次登陆，自动生成用户信息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/auth")
    public void auth(@RequestParam String code, HttpServletResponse response) throws IOException {
        log.info("execute /user/auth,code={}", code);
        OpenId openId = wechatService.getOpenId(code);

        //构造查询条件
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.where("OPENID={0}", openId.getOpenid());
        User user = userService.selectOne(ew);

        if (user == null) {
            log.info("openId为{}的用户不存在，为第一次登陆，自动绑定创建用户信息", openId.getOpenid());
            WxUserInfo wxUserInfo = wechatService.getUserInfo(openId.getOpenid(), openId.getAccess_token());
            //生成用户信息
            user = userService.wxInitUserByWx(wxUserInfo);
        }
        //stringRedisTemplate.opsForValue().set("admin", "wechat");
        Cookie cookie = new Cookie("USERID", String.valueOf(user.getId()));
        cookie.setDomain(domain);
        cookie.setPath("/");
        response.addCookie(cookie);

        response.sendRedirect(INDEX_URL);
//        return new RedirectView(INDEX_URL);
    }

    /**
     * 微信端根据cookie获取用户信息接口
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "userinfo", method = RequestMethod.GET)
    @ResponseBody
    public String userInfo(@CookieValue("USERID") Integer userId) {
        ResponseDTO<UserInfoResult> res = userService.wxGetUserInfo(userId);

        return JSON.toJSONString(res);
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    @ResponseBody
    public String login(String username, String password) {
        ResponseDTO dto = userService.adminLogin(username, password);

        return JSON.toJSONString(dto);
    }

    @RequestMapping(value = "userlist", method = RequestMethod.GET)
    @ResponseBody
    @AuthOperate
    public String userList(Integer currentPage, Integer pageSize, String searchCondition) {
        ResponseDTO<List<User>> dto = userService.getUserList(currentPage, pageSize, searchCondition);

        return JSON.toJSONString(dto);
    }
}
